package com.example.block_chain.controller.faculty;

import com.example.block_chain.RabbitMQ.Producer;
import com.example.block_chain.common.AppHttpCodeEnum;
import com.example.block_chain.common.ResponseResult;
import com.example.block_chain.common.SystemParameters;
import com.example.block_chain.domain.dto.FacultyDto;
import com.example.block_chain.domain.pbft.VoteInfo;
import com.example.block_chain.domain.pojo.Admin;
import com.example.block_chain.domain.pojo.Faculty;
import com.example.block_chain.service.blockChain.BlockService;
import com.example.block_chain.service.faculty.FacultyService;
import com.example.block_chain.utils.KeyValueReaderUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/*
 *@description: 学院相关接口
 *@author: hisen
 *@Time: 2024/3/4  16:10
 */
@RestController
public class FacultyController {

    @Resource
    FacultyService facultyService;

    @Resource
    BlockService blockService;

    @Resource
    Producer producer;

    @GetMapping("/getFaculty")
    public ResponseResult getFaculty(@RequestParam String schoolCode) {
        if (schoolCode == null) return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
        List<Faculty> facultyLis = facultyService.getFacultyBySchoolCode(schoolCode);
        return ResponseResult.okResult(facultyLis);
    }

    @PostMapping("/addFaculty")
    public ResponseResult addFaculty(@RequestBody FacultyDto dto, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        if (!Objects.equals(admin.getAuthority(), SystemParameters.AUTHORITY_0.toString())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AUTHORITY_DEFICIENCY);
        }
        if (KeyValueReaderUtil.getDigestByCode(dto.getSchoolCode(), SystemParameters.SCHOOL_FILE_PATH) == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SCHOOL_NO_EXISTS);
        }
        Faculty faculty = new Faculty();
        BeanUtils.copyProperties(dto, faculty);
        //学院上链
        if (facultyService.getFaculty(faculty.getFacultyCode()) != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CODE_EXISTS);
        }
        facultyService.save(faculty);

        VoteInfo voteInfo = blockService.createFacultyBlock(faculty.getSchoolCode(), faculty.getFacultyCode());
        producer.sendMessage(voteInfo);
        return ResponseResult.okResult();
    }
}
